﻿using Microsoft.Extensions.Logging;
using System;
using System.Threading;
namespace Odyssey.Application.Implementations
{
    public class ApplicationLifetime : IApplicationLifetime
    {
        private readonly CancellationTokenSource _startedSource = new CancellationTokenSource();
        private readonly CancellationTokenSource _stoppedSource = new CancellationTokenSource();
        private readonly ILogger _logger;


        public CancellationToken ApplicationStarted => _startedSource.Token;

        public CancellationToken ApplicationStopped => _stoppedSource.Token;

        public ApplicationLifetime(ILogger<ApplicationLifetime> logger)
        {
            _logger = logger;
        }


        public void StartNotify()
        {
            lock (_startedSource)
            {
                try
                {
                    ExecuteHandlers(_startedSource);
                }
                catch (Exception ex)
                {
                    _logger.LogError("开始应用失败。", ex);
                }
            }
        }


        public void StopNotify()
        {
            lock (_stoppedSource)
            {
                try
                {
                    ExecuteHandlers(_stoppedSource);
                }
                catch (Exception ex)
                {
                    _logger.LogError("停止应用失败。", ex);
                }
            }
        }


        private void ExecuteHandlers(CancellationTokenSource cancellationTokenSource)
        {
            if (cancellationTokenSource.IsCancellationRequested)
            {
                return;
            }
            cancellationTokenSource.Cancel(false);
        }
    }
}
